<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :search.sync="search"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :row-class-name="tableRowClassName"
      @cell-dblclick="handleRowClick"
    >
      <template slot="icon" slot-scope="scope">
        <i :class="scope.row.icon" style="font-size: 24px"></i>
      </template>
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择 工单号" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoCommonModal"></el-button>
        </el-input>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" icon="el-icon-view" size="small" @click.stop="viewPartInfo(row)">物料详情</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <!-- <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
      </template> -->
    </avue-crud>
    <el-dialog title="详情" :visible.sync="showDetailDialog" width="60%" append-to-body="true">
      <avue-crud ref="detailCrud" :option="detailOption" :table-loading="detailLoading" :data="detailData" @refresh-change="detailRefreshChange">
        <template slot-scope="{ row }" slot="menu">
          <el-button type="text" icon="el-icon-view" size="small" @click.stop="viewPackInfo(row)" :disabled="!recordId">包装详情</el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <export-comp ref="exportComp" page-api-url="" :option="option" :page="page" reportCode="productPack_export" :query="query" file-name="成品包装"> </export-comp>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex';
import exportComp from '@/components/export-comp';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, getDetail } from '@/api/product/preProcessingRecord';
import exportExcel from '@/components/export-excel';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  name: 'ReportFinishedProductPackageQuery',
  components: {
    CommonModalTemplate,
    exportExcel,
    userTableConfig,
    exportComp
  },
  mixins: [userConfig()],
  data() {
    return {
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      exprotVisible: false,
      exportData: [],
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      query: {
        isExportAll: true
      },
      loading: true,
      search: {},
      selectionList: [],
      option: {
        height: 'calc(100vh - 480px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        searchLabelWidth: 100,
        border: true,
        editBtn: false,
        viewBtn: false,
        selection: true,
        delBtn: false,
        addBtn: false,
        dialogClickModal: false,
        index: true,
        indexLabel: '序号',
        searchMenuPosition: 'right',
        menu: true,
        columnBtn: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '产品名称',
            prop: 'partName',
            search: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            search: true
          },
          {
            label: '工单计划数量',
            prop: 'planQuantity'
          },
          {
            label: '前加工物料种类',
            prop: 'partCount'
          },
          {
            label: '状态',
            prop: 'status',
            search: true,
            type: 'select',
            dicData: [
              {
                label: '待加工',
                value: 0
              },
              {
                label: '加工中',
                value: 1
              },
              {
                label: '已加工',
                value: 2
              }
            ],
            html: true,
            formatter: (val) => {
              if (val.status == 0) {
                return '<b style="color:#d9001b">待加工</b>';
              } else if (val.status == 1) {
                return '<b style="color:#f8a786">加工中</b>';
              } else {
                return '<b style="color:#95f204">已加工</b>';
              }
            }
          },
          {
            label: '计划开始时间',
            prop: 'startTime'
          },
          {
            label: '计划结束时间',
            prop: 'endTime'
          }
        ]
      },
      data: [],
      selectIndex: '',
      detailOption: {
        height: '500px',
        calcHeight: 30,
        tip: false,
        border: true,
        selection: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        editBtn: false,
        delBtn: false,
        menu: true,
        columnBtn: false,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '加工数量',
            prop: 'unitQuantity'
          }
        ]
      },
      showDetailDialog: false,
      detailLoading: false,
      detailData: [],
      showPackDetailDialog: false,
      packDetailLoading: false,
      packDetailData: [],
      rowParams: {},
      recordId: ''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleSelectData(val) {
      let current = 1;
      let pageSize = this.page.pageSize;
      if (val === 'all') {
        // 接口返回上限500条数据
        pageSize = 500;
      } else {
        current = this.page.currentPage;
      }
      const page = {
        current,
        pageSize
      };
      this.onLoad(page);
    },
    handleExport() {
      let data = [];
      this.data.forEach((item) => {
        let children = [];
        item.level = '外包装';
        if (item.children && item.children.length > 0) {
          children = item.children;
        }
        this._forEach(children, (c) => {
          c.level = '内包装';
        });
        data.push(item, ...children);
      });
      console.log(data, '8899');
      this.exportData = this._cloneDeep(data);
      this.exprotVisible = true;
    },
    handleClose(val) {
      this.exprotVisible = false;
      this.data = this.exportData.splice(0, this.page.pageSize);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    forFunction(list) {
      for (let j = 0; j < list.length; j++) {
        if (this.query.packNo) {
          if (list[j].packNo === this.query.packNo) {
            this.selectIndex = j + this.option.expandRowKeys.length;
            break;
          }
          if (list[j].packNo != this.query.packNo && list[j].children) {
            this.option.expandRowKeys.push(list[j].packNo);
            this.forFunction(list[j].children);
          }
        }
        if (this.query.productSequenceNumber) {
          if (list[j].isContain && list[j].isContain != null) {
            this.selectIndex = j + this.option.expandRowKeys.length;
            break;
          }
          if (!list[j].isContain && list[j].children) {
            this.option.expandRowKeys.push(list[j].packNo);
            this.forFunction(list[j].children);
          }
        }
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === this.selectIndex) {
        return 'scan-entry-row';
      }
      return '';
    },
    openWorkOrderNoCommonModal() {
      this.modalName = 'workOrderNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderNoModal':
          this.search.workOrderNo = this._get(rowData, 'orderNo', '');
          break;
        default:
          break;
      }
      if (rowData.sequenceNumber) {
        this.$router.push({
          path: '/report/forward-trace-back-to',
          query: { sequenceNumber: rowData.sequenceNumber }
        });
      }
    },
    //表格双击
    handleRowClick(row, column, cell, event) {
      if (column.label == '工单号' && row.workOrderNo) {
        this.$router.push({
          path: '/product/workOrderProgress',
          query: { workOrderNo: row.workOrderNo }
        });
      }
    },
    /**
     * 查看产品序列号
     */
    viewPartInfo(row) {
      this.showDetailDialog = true;
      this.detailLoading = true;
      this.recordId = row.id;
      this.rowParams = { configId: row.configId, workOrderId: row.workOrderId };
      this.queryDetailList(this.rowParams);
    },
    queryDetailList(params) {
      getDetail(params).then((res) => {
        const data = res.data.data;
        this.detailData = data;
        this.detailLoading = false;
      });
    },
    detailExport() {
      this.$refs.detailExportComp.visible = true;
    },
    detailRefreshChange() {
      this.queryDetailList(this.rowParams);
    },
    viewPackInfo(row) {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '包装明细',
        url: `/api/mes-product/preprocess/record/detail-packing?partNo=${row.partNo}&recordId=${this.recordId}`,
        isPage: false,
        rowSelectionType: 'single',
        readonly: true,
        columnDefs: [
          {
            label: '包装条码',
            prop: 'packNo'
          },
          {
            label: '数量',
            prop: 'packQuantity'
          }
        ]
      };
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table .scan-entry-row {
  background: #caf982;
}
</style>
